package wsepForum.ui.jaxcent.states;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Map;

import jaxcent.HtmlImage;
import jaxcent.Jaxception;
import wsepForum.ui.jaxcent.IXContext;

public class XStatsQuery extends AXQuery {
	/*****************************
	 * MEMBERS                   *
	 *****************************/
	final static private int USER_HOUR = 0;
	final static private int MSG_HOUR = 1;
	final static private int MSG_DAY = 2;

	/*****************************
	 * CONSTRUCTOR               *
	 *****************************/
	public XStatsQuery(IXContext context)
	{
		super(context);
		dealWithTypeChange(USER_HOUR);
	}

	/*****************************
	 * METHODS                   *
	 *****************************/
	@Override
	protected void construct() {
		String title,extraFields,types;
		title = "Statistics";
		extraFields = "";
		types =
			"<option>Users per hour</option>" +
			"<option>Messages per hour</option>" +
			"<option>User's messages per day</option>";

		construct(title,extraFields,types);
	}

	@Override
	protected void dealWithTypeChange(int index) {
		this.type = index;
		try {
			switch (this.type) {
			case USER_HOUR:
				this.xDesc.setInnerText("How many user was online in each hour of a specific date");
				loadUsers(false);
				break;
			case MSG_HOUR:
				this.xDesc.setInnerText("How many messages posted each hour of a specific date");
				loadUsers(false);
				break;
			case MSG_DAY:
				this.xDesc.setInnerText("How many message a specific user posted each day for 31 days, starting from a specific date");
				loadUsers(true);
				break;
			}
		} catch (Jaxception e) {
			this.context.getPage().showMessageDialog("cannot manipulate page!\n"+e.getMessage());

		}
	}

	@Override
	@SuppressWarnings("unchecked")
	protected void dealWithQuery(Map pageData) {
		try {
			BufferedImage img = null;
			Date date = getDate(1,pageData);
			switch(this.type) {
			case USER_HOUR:
				img = this.context.getSession().getHandler().makeUserCountStatistics(date);
				break;
			case MSG_HOUR:
				img = this.context.getSession().getHandler().makeMessageCountStatistics(date);
				break;
			case MSG_DAY:
				img = this.context.getSession().getHandler().makeUserMessagePerDay(date, getUserName(pageData));
				break;
			}
			showResult(img);
		} catch (Exception e) {
			this.context.getPage().showMessageDialog("You are unauthorized to do this!");
		}
	}

	private void showResult(BufferedImage result) {
		try {
			this.xResults.setInnerHTML("<hr /><h2>Result</h2><br /><img id=\"ximage\">");
			HtmlImage xImage = new HtmlImage(this.context.getPage(),"ximage");
			xImage.setSrc( result, "jpeg" );
		} catch (Jaxception e) {
			this.context.getPage().showMessageDialog("cannot display result!\n"+e.getMessage());
		}
	}
}
